package com.im.server.modules.websocket.handler;

import com.alibaba.fastjson.JSONObject;
import com.im.server.common.annotation.HandleType;
import com.im.server.common.utils.UuidUtil;
import com.im.server.modules.chat.entity.ImChatRecord;
import com.im.server.modules.chat.entity.ImChatRecordVo;
import com.im.server.modules.chat.service.ImChatRecordService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 描述：点对点单聊 处理器
 * <p>
 * 作者：Ostrich Hu
 * 时间：2019/12/17 14:42 星期二
 */
@HandleType("single")
@Component
public class ChatSingleHandler extends AbstractWebSocketHandler {

    private final ImChatRecordService imChatRecordService;

    public ChatSingleHandler(ImChatRecordService imChatRecordService) {
        this.imChatRecordService = imChatRecordService;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public boolean saveOrUpdateChatList(String event) {
        boolean flag = false;
        ImChatRecordVo imChatRecordVo = JSONObject.parseObject(event, ImChatRecordVo.class);
        String senderId = imChatRecordVo.getSenderId();
        String receiverId = imChatRecordVo.getReceiverId();

        //1.插入聊天记录
        ImChatRecord imChatRecord = new ImChatRecord();
        imChatRecord.setId(UuidUtil.randomUUID());
        imChatRecord.setSenderId(senderId);
        imChatRecord.setSendTime(imChatRecordVo.getSendTime());
        imChatRecord.setMsgContent(imChatRecordVo.getMsgContent());
        if (imChatRecordService.save(imChatRecord)) {
            imChatRecordVo.setChatId(imChatRecord.getId());
            imChatRecordVo.setIsRead(0);
            //2.分别新增根据消息发送人、消息接收人与聊天记录关系
            flag = imChatRecordService.saveUserImRelation(imChatRecordVo);
            imChatRecordVo.setSenderId(receiverId);
            imChatRecordVo.setReceiverId(senderId);
            flag = imChatRecordService.saveUserImRelation(imChatRecordVo);
        }

        return flag;
    }
}
